package cn.how2go.api.controller;


import cn.how2go.api.common.CommonResult;
import cn.how2go.api.common.MessageResult;
import cn.how2go.api.common.ReadBin;
import cn.how2go.api.entity.Cone;
import cn.how2go.api.entity.Fence;
import cn.how2go.api.service.ConeService;
import cn.how2go.api.service.DeviceService;
import cn.how2go.api.service.FenceService;
import cn.how2go.api.util.DateUtil;
import cn.how2go.api.vo.FenceVo;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2020-05-31
 */
@Api(value = "电子围栏",description = "电子围栏信息的管理")
@RestController
@RequestMapping("/api/fence")
public class FenceController {
    @Autowired
    private FenceService fenceService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ConeService coneService;

    @ApiOperation(value="查询未删除的电子围栏列表", notes="")
    @RequestMapping(value = "listFences", method = RequestMethod.GET)
    public CommonResult listFences(){
        EntityWrapper<Fence> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("State",1);
        entityWrapper.eq("Valid",1);
        entityWrapper.orderBy("RecordTime",false);
        List<Fence> list = fenceService.selectList(entityWrapper);
        List<FenceVo> result = new ArrayList<>();
        for(Fence bean:list){
            FenceVo fenceVo = new FenceVo();
            fenceVo.setId(bean.getId());
            fenceVo.setSource(bean.getSource());
            fenceVo.setName(bean.getName());
            fenceVo.setRule(bean.getRule());
            fenceVo.setValid(bean.getValid());
            fenceVo.setType(bean.getType());
            fenceVo.setState(bean.getState());
            fenceVo.setStartTime(bean.getStartTime().toString());
            fenceVo.setEndTime(bean.getEndTime().toString());
            fenceVo.setPtNum(bean.getPtNum());
            if(bean.getPtNum()>0) {
                try {
                    String points ="";
                    double[] doubles = new double[bean.getPoints().length/8];
                    int pt =0;
                    for(int i=0;i<bean.getPoints().length;i++){
                        byte[] tem = new byte[8];
                        for(int j=0;j<8;++j){
                            tem[j]= bean.getPoints()[i];
                            i++;
                        }
                        i=i-1;
                        doubles[pt] = ReadBin.bytes2Double(tem);
                        pt++;
                    }
                    for(double d:doubles){
                        points +=String.valueOf(d)+",";
                    }
                    fenceVo.setPoints(points);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(bean.getSource().equals("0")){
                EntityWrapper<Cone> entityWrapper1 = new EntityWrapper<>();
                entityWrapper1.eq("Fence",bean.getId());
                entityWrapper1.last("limit 1");
                Cone cone = coneService.selectOne(entityWrapper1);
                if(cone!=null)
                    fenceVo.setGroup(cone.getGroup());
            }
            result.add(fenceVo);
        }
        return CommonResult.success(result);
    }

    @ApiOperation(value="查询有效的电子围栏列表显示到地图", notes="")
    @RequestMapping(value = "listFence", method = RequestMethod.GET)
    public CommonResult listFence(){
        EntityWrapper<Fence> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("Valid\n",1);
        entityWrapper.orderBy("RecordTime",false);
        List<Fence> list = fenceService.selectList(entityWrapper);
        List<FenceVo> result = new ArrayList<>();
        for(Fence bean:list){
            FenceVo fenceVo = new FenceVo();
            fenceVo.setId(bean.getId());
            fenceVo.setSource(bean.getSource());
            fenceVo.setName(bean.getName());
            fenceVo.setRule(bean.getRule());
            fenceVo.setValid(bean.getValid());
            fenceVo.setType(bean.getType());
            fenceVo.setState(bean.getState());
            fenceVo.setStartTime(bean.getStartTime().toString());
            fenceVo.setEndTime(bean.getEndTime().toString());
            fenceVo.setPtNum(bean.getPtNum());
            if(bean.getPtNum()>0) {
                try {
                    String points ="";
                    double[] doubles = new double[bean.getPoints().length/8];
                    int pt =0;
                    for(int i=0;i<bean.getPoints().length;i++){
                        byte[] tem = new byte[8];
                        for(int j=0;j<8;++j){
                            tem[j]= bean.getPoints()[i];
                            i++;
                        }
                        i=i-1;
                        doubles[pt] = ReadBin.bytes2Double(tem);
                        pt++;
                    }
                    for(double d:doubles){
                        points +=String.valueOf(d)+",";
                    }
                    fenceVo.setPoints(points);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            result.add(fenceVo);
        }
        return CommonResult.success(list);
    }

    @ApiOperation(value="获取电子围栏", notes="根据ID获取电子围栏信息")
    @RequestMapping(value = "getFenceById",method = {RequestMethod.POST,RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "ID", value = "UUID", required = true, dataType = "String"),
    })
    public CommonResult getFenceById(@RequestParam(value = "ID") String id){
        EntityWrapper<Fence> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",id);
        entityWrapper.last("limit 1");
        Fence fence = fenceService.selectOne(entityWrapper);
        FenceVo fenceVo = new FenceVo();
        BeanUtils.copyProperties(fence,fenceVo);
        if(fence.getSource().equals("0")){
            EntityWrapper<Cone> entityWrapper1 = new EntityWrapper<>();
            entityWrapper1.eq("Fence",fence.getId());
            entityWrapper1.last("limit 1");
            Cone cone = coneService.selectOne(entityWrapper1);
            if(cone!=null)
                fenceVo.setGroup(cone.getGroup());
        }
        try {
            if(fence.getPtNum()>0) {
                try {
                    String points ="";
                    double[] doubles = new double[fence.getPoints().length/8];
                    int pt =0;
                    for(int i=0;i<fence.getPoints().length;i++){
                        byte[] tem = new byte[8];
                        for(int j=0;j<8;++j){
                            tem[j]= fence.getPoints()[i];
                            i++;
                        }
                        i=i-1;
                        doubles[pt] = ReadBin.bytes2Double(tem);
                        pt++;
                    }
                    for(double d:doubles){
                        points +=String.valueOf(d)+",";
                    }
                    fenceVo.setPoints(points);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(fence == null){
            return CommonResult.fail("获取失败");
        }
        return CommonResult.success(fenceVo);
    }

    @ApiOperation(value="创建电子围栏信息", notes="创建一个电子围栏的信息，RecordTime后台生成")
    @RequestMapping(value = "saveFence", method = RequestMethod.POST)
    public CommonResult saveFence(@RequestBody FenceVo fence){
        if(fence.getSource().equals("1")) {
            if(fence.getPtNum()==0){
                return CommonResult.fail("没有画围栏信息，请在地图上画围栏信息");
            }
            Fence bean = new Fence();
            bean.setId(UUID.randomUUID().toString());
            bean.setName(fence.getName());
            bean.setRule(fence.getRule());
            bean.setValid(fence.getValid());
            bean.setType(fence.getType());
            bean.setState(1);
            fence.setStartTimeDate(DateUtil.toDateTime("2008-01-01 "+fence.getStartTime()));
            fence.setEndTimeDate(DateUtil.toDateTime("2008-01-01 "+fence.getEndTime()));
            bean.setStartTime(new Time(fence.getStartTimeDate().getTime()));
            bean.setEndTime(new Time(fence.getEndTimeDate().getTime()));
            bean.setPtNum(fence.getPtNum());
            bean.setRecordTime(new Date());
            if (fence.getPtNum() >= 3) {
                bean.setSource("1");
                if (fence.getPoints() != null) {
                    //处理String转BLOB
                    try {
                        String[] strValue = fence.getPoints().split(",");
                        byte[] points = new byte[strValue.length * 8];
                        int i = 0;
                        for (String value : strValue) {
                            double dvalue = Double.parseDouble(value);
                            byte[] tem = ReadBin.double2Bytes(dvalue);
                            for (int j = 0; j < 8; j++) {
                                points[i * 8 + j] = tem[j];
                            }
                            i++;
                        }
                        bean.setPoints(points);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            boolean flag = fenceService.insert(bean);
            if (!flag) {
                return CommonResult.fail("保存失败");
            }
            return CommonResult.success(fence);
        }else{
            Fence bean = new Fence();
            bean.setId(UUID.randomUUID().toString());
            bean.setName(fence.getName());
            bean.setRule(fence.getRule());
            bean.setValid(fence.getValid());
            bean.setType(fence.getType());
            bean.setState(1);
            bean.setSource(fence.getSource());
            fence.setStartTimeDate(DateUtil.toDateTime("2008-01-01 "+fence.getStartTime()));
            fence.setEndTimeDate(DateUtil.toDateTime("2008-01-01 "+fence.getEndTime()));
            bean.setStartTime(new Time(fence.getStartTimeDate().getTime()));
            bean.setEndTime(new Time(fence.getEndTimeDate().getTime()));
            bean.setPtNum(fence.getPtNum());
            bean.setRecordTime(new Date());
            boolean flag = fenceService.insert(bean);
            //更新人员设备
            Cone cone = new Cone();
            cone.setFence(bean.getId());
            cone.setGroup(fence.getGroup());
            coneService.updateByGroup(cone);

            if (!flag) {
                return CommonResult.fail("保存失败");
            }
            return CommonResult.success(fence);
        }
    }

    @ApiOperation(value="修改电子围栏信息", notes="修改一个电子围栏的信息，RecordTime后台生成")
    @RequestMapping(value = "editFence", method = RequestMethod.POST)
    public CommonResult editFence(@RequestBody FenceVo fence){
        Fence bean = new Fence();
        bean.setSource(fence.getSource());
        bean.setName(fence.getName());
        bean.setRule(fence.getRule());
        bean.setValid(fence.getValid());
        bean.setType(fence.getType());
        bean.setState(1);
        fence.setStartTimeDate(DateUtil.toDateTime("2008-01-01 "+fence.getStartTime()));
        fence.setEndTimeDate(DateUtil.toDateTime("2008-01-01 "+fence.getEndTime()));
        bean.setStartTime(new Time(fence.getStartTimeDate().getTime()));
        bean.setEndTime(new Time(fence.getEndTimeDate().getTime()));
        bean.setPtNum(fence.getPtNum());
        bean.setRecordTime(new Date());
        if(fence.getPoints()!=null) {
            //处理String转BLOB
            try {
                String[] strValue = fence.getPoints().split(",");
                byte[] points = new byte[strValue.length * 8];
                int i = 0;
                for (String value : strValue) {
                    double dvalue = Double.parseDouble(value);
                    byte[] tem = ReadBin.double2Bytes(dvalue);
                    for (int j = 0; j < 8; j++) {
                        points[i * 8 + j] = tem[j];
                    }
                    i++;
                }
                bean.setPoints(points);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        EntityWrapper<Fence> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",fence.getId());
        boolean flag = fenceService.update(bean,entityWrapper);
        if(!flag){
            return CommonResult.fail("修改失败");
        }
        return CommonResult.success(fence);
    }

    @ApiOperation(value="软删除电子围栏信息", notes="软删除一个电子围栏的信息，RecordTime后台生成")
    @RequestMapping(value = "deleteFence", method = RequestMethod.GET)
    public MessageResult deleteFence(@RequestParam String id){
        EntityWrapper<Fence> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",id);
        Fence fence = new Fence();
        fence.setState(0);
        boolean flag = fenceService.update(fence,entityWrapper);
        EntityWrapper<Cone> coneEntityWrapper = new EntityWrapper<>();
        coneEntityWrapper.eq("Fence",id);
        Cone cone =new Cone();
        cone.setFence("");
        coneService.update(cone,coneEntityWrapper);
        if(!flag){
            return MessageResult.getError("500","删除失败");
        }
        return MessageResult.getSuccess("删除成功");
    }
}

